<template>
  <div class="analysis-container">
    <Transition name="fade">
      <!-- 顶部通栏：上下文摘要（整合元数据） -->
      <header class="context-summary" v-if="conversationImported && analysisResult">
        <div class="context-summary-content">
          <div class="context-summary-row">
            <div class="metadata-overview">
              <div class="metadata-items">
                <div class="metadata-item" key="report-id">
                  <span class="label">报告编号</span>
                  <span class="value">{{ analysisResult.reportId }}</span>
                </div>
                <div class="metadata-item" key="dialogue-type">
                  <span class="label">对话类型</span>
                  <span class="type-badge" :class="analysisResult.contextSummary.dialogueType">
                    {{ getDialogueTypeIcon(analysisResult.contextSummary.dialogueType) }}
                    {{ analysisResult.contextSummary.dialogueType }}
                  </span>
                </div>
                <div class="metadata-item" key="analysis-time">
                  <span class="label">分析时间</span>
                  <span class="value">{{ new Date().toLocaleString() }}</span>
                </div>
              </div>
            </div>
            
            <div class="participant-cards">
              <div class="participant-list">
                <div v-for="user in analysisResult.contextSummary.participants" 
                     :key="user" 
                     class="participant-card"
                     :class="{ 'active': getEmotionState(user) !== 'neutral' }">
                  <div class="participant-avatar">
                    <div class="emotion-bubble" :class="getEmotionState(user)"></div>
                    <div class="avatar-model"></div>
                  </div>
                  <div class="participant-info">
                    <h3 class="participant-name">{{ getSpeakerLabel(user) }}</h3>
                    <div class="progress-ring">
                      <div class="progress-fill" :style="{ width: getGoalProgress(user) + '%' }"></div>
                    </div>
                    <span class="progress-text">目标达成度 {{ getGoalProgress(user) }}%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>
    </Transition>

    <!-- 主要分析区域 -->
    <main class="analysis-main">
      <!-- 导入对话界面 -->
      <Transition name="fade">
        <section class="analysis-section" v-if="!conversationImported">
          <div class="empty-state">
            <div class="empty-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                <line x1="9" y1="10" x2="15" y2="10"/>
                <line x1="9" y1="14" x2="15" y2="14"/>
              </svg>
            </div>
            <h2 class="empty-title">开始对话分析</h2>
            <p class="empty-text">导入对话内容，让我们一起深入分析对话中的情感、策略和互动模式</p>
            <div class="empty-features">
              <div class="feature-item">
                <div class="feature-icon">📊</div>
                <div class="feature-text">情感分析</div>
              </div>
              <div class="feature-item">
                <div class="feature-icon">🎯</div>
                <div class="feature-text">策略洞察</div>
              </div>
              <div class="feature-item">
                <div class="feature-icon">💡</div>
                <div class="feature-text">优化建议</div>
              </div>
            </div>
            <ConversationImport @analysis-complete="handleAnalysisComplete" />
          </div>
        </section>
      </Transition>

      <!-- 分析结果区域 -->
      <TransitionGroup name="slide-up" tag="div" class="analysis-sections" v-if="conversationImported && analysisResult">
        <!-- 情感时间轴 -->
        <section class="analysis-section chat-analysis-section" key="emotional-timeline" v-show="analysisResult.interactionAnalysis.emotionalTimeline.length > 0">
          <h3 class="section-title">
            <span class="section-icon">📊</span>
            情感时间轴
          </h3>
          <EmotionalTimeline 
            :dialogueTurns="analysisResult.interactionAnalysis.emotionalTimeline"
            :critical-junctions="analysisResult.strategicInsights.criticalJunctions"
          />
        </section>

        <!-- 证据网络 -->
        <section class="analysis-section" key="evidence-network" v-show="networkData.nodes.length > 0">
          <h3 class="section-title">
            <span class="section-icon">🔄</span>
            证据网络
          </h3>
          <EvidenceNetwork 
            :network-data="networkData"
          />
        </section>

        <!-- 战略矩阵 -->
        <section class="analysis-section" key="strategic-matrix">
          <h3 class="section-title">
            <span class="section-icon">🎯</span>
            战略矩阵
          </h3>
          <StrategicMatrix 
            :matrix-data="analysisResult.strategicInsights.motivationMatrix"
          />
        </section>

        <!-- 冲突仪表盘 -->
        <section class="analysis-section" key="conflict-dashboard">
          <h3 class="section-title">
            <span class="section-icon">⚡</span>
            冲突评估
          </h3>
          <ConflictDashboard 
            :detected-issues="analysisResult.conflictAssessment.detectedIssues"
            :risk-evaluation="analysisResult.conflictAssessment.riskEvaluation"
          />
        </section>

        <!-- 优化建议 -->
        <section class="analysis-section" key="optimization-recommendations">
          <h3 class="section-title">
            <span class="section-icon">💡</span>
            优化建议
          </h3>
          <OptimizationRecommendations 
            :immediate-actions="analysisResult.optimizationRecommendations.immediateActions"
            :preventive-measures="analysisResult.optimizationRecommendations.preventiveMeasures"
          />
        </section>
      </TransitionGroup>
    </main>

    <!-- 浮动聊天窗口 -->
    <Transition name="fade">
      <ChatWindow 
        v-if="showChatWindow || showChatButton"
        :initial-messages="[]"
        @close="handleChatClose"
        @reopen="showChatWindow = true"
        @send="handleChatMessage"
        :dialogue-turns="analysisResult.interactionAnalysis.emotionalTimeline"
      />
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import type { 
  AnalysisResult, 
  NetworkNode, 
  NetworkLink
} from '../types/dialogue';
import ConversationImport from '../components/analysis/ConversationImport.vue';
import EmotionalTimeline from '../components/analysis/EmotionalTimeline.vue';
import EvidenceNetwork from '../components/analysis/EvidenceNetwork.vue';
import StrategicMatrix from '../components/analysis/StrategicMatrix.vue';
import ConflictDashboard from '../components/analysis/ConflictDashboard.vue';
import OptimizationRecommendations from '../components/analysis/OptimizationRecommendations.vue';
import ChatWindow from '../components/analysis/ChatWindow.vue';
import { useAnalysisStore } from '../stores/analysis';

// 状态管理
const analysisStore = useAnalysisStore();
const conversationImported = ref(false);
const showChatWindow = ref(false);
const showChatButton = ref(false);

const analysisResult = ref<AnalysisResult>({
  reportId: '',
  contextSummary: {
    participants: [],
    dialogueType: ''
  },
  interactionAnalysis: {
    emotionalTimeline: [],
    pragmaticFeatures: []
  },
  strategicInsights: {
    motivationMatrix: {},
    criticalJunctions: [{
      turn: 0,
      description: '',
      impact: '',
      triggers: [],
      impactScore: 0
    }]
  },
  conflictAssessment: {
    detectedIssues: [{
      issue: '',
      severity: 'low',
      participants: [],
      type: '',
      evidence: [],
      confidence: 'medium'
    }],
    riskEvaluation: 'low'
  },
  optimizationRecommendations: {
    immediateActions: [{
      action: '',
      priority: 'low',
      impact: '',
      strategy: '保持开放和理解的态度',
      example: '',
      applicability: 0
    }],
    preventiveMeasures: [{
      measure: '',
      timeframe: 'short',
      effectiveness: 0,
      method: '定期进行深入交流',
      example: '',
      priority: 'low'
    }]
  }
});

// 计算属性
const networkData = computed<() => { nodes: NetworkNode[], links: NetworkLink[] }>(() => {
  const nodes: NetworkNode[] = [];
  const links: NetworkLink[] = [];
  
  // 从动机矩阵创建网络数据
  Object.entries(analysisResult.value.strategicInsights.motivationMatrix).forEach(([participant, goals]) => {
    // 为每个参与者创建一个中心节点
    const participantId = `participant-${participant}`;
    nodes.push({
      id: participantId,
      label: participant,
      type: 'goal',
      weight: 1,
      user: participant
    });

    goals.forEach((goal, index) => {
      // 为每个目标创建一个节点
      const goalId = `goal-${participant}-${index}`;
      nodes.push({
        id: goalId,
        label: goal.goal,
        type: 'goal',
        weight: goal.confidence === 'high' ? 1 : 0.7,
        user: participant
      });

      // 连接参与者和目标
      links.push({
        source: participantId,
        target: goalId,
        strength: goal.confidence === 'high' ? 1 : 0.7,
        type: 'supports'
      });

      // 为每个支持证据创建节点和连接
      goal.supportingEvidence.forEach((evidence, evidenceIndex) => {
        const evidenceId = `evidence-${participant}-${index}-${evidenceIndex}`;
        nodes.push({
          id: evidenceId,
          label: evidence,
          type: 'evidence',
          weight: 0.5,
          user: participant
        });

        links.push({
          source: goalId,
          target: evidenceId,
          strength: 0.5,
          type: 'supports'
        });
      });
    });
  });

  return { nodes, links };
});

// 生命周期钩子
onMounted(() => {
  analysisStore.$subscribe((_: string, state: Record<string, unknown>) => {
    if (state.analysisData) {
      analysisResult.value = {
        ...analysisResult.value,
        ...state.analysisData
      };
      conversationImported.value = true;
      showChatWindow.value = true;
      showChatButton.value = false;
    }
  });
});

onMounted(() => {
  // ... 保持现有的挂载逻辑不变
});

// 方法
const getEmotionState = (user: string): 'positive' | 'negative' | 'neutral' => {
  if (!analysisResult.value) return 'neutral';
  
  const userEmotions = analysisResult.value.interactionAnalysis.emotionalTimeline
    .filter(turn => turn.speaker === user)
    .map(turn => turn.emotion.type);
  
  const lastEmotion = userEmotions[userEmotions.length - 1];
  return lastEmotion || 'neutral';
};

const getGoalProgress = (user: string): number => {
  if (!analysisResult.value) return 0;
  
  const userGoals = analysisResult.value.strategicInsights.motivationMatrix[user] || [];
  const totalConfidence = userGoals.reduce((sum, goal) => {
    return sum + (goal.confidence === 'high' ? 1 : goal.confidence === 'medium' ? 0.6 : 0.3);
  }, 0);
  
  return Math.min(totalConfidence * 25, 100);
};

const getDialogueTypeIcon = (type: string): string => {
  const iconMap: Record<string, string> = {
    '情感交流': '❤️',
    '工作沟通': '💼',
    '日常对话': '💬',
    '冲突对话': '⚡',
    '协商讨论': '🤝'
  };
  
  return iconMap[type] || '💬';
};

const getSpeakerLabel = (speaker: string): string => {
  const speakerMap: Record<string, string> = {
    'A': 'A',
    'B': 'B',
    'man': '男性',
    'woman': '女性',
    'user': '用户',
    'assistant': '助手'
  };
  
  return speakerMap[speaker] || speaker;
};

const handleAnalysisComplete = (result: AnalysisResult) => {
  analysisResult.value = {
    ...result,
    strategicInsights: {
      ...result.strategicInsights,
      criticalJunctions: result.strategicInsights.criticalJunctions.map(junction => ({
        ...junction,
        triggers: junction.triggers || [],
        impactScore: junction.impactScore || 0
      }))
    },
    conflictAssessment: {
      ...result.conflictAssessment,
      detectedIssues: result.conflictAssessment.detectedIssues.map(issue => ({
        ...issue,
        type: issue.type || '',
        evidence: issue.evidence || [],
        confidence: issue.confidence || 'medium',
        severity: issue.severity || 'low'
      })),
      riskEvaluation: result.conflictAssessment.riskEvaluation || 'low'
    },
    optimizationRecommendations: {
      ...result.optimizationRecommendations,
      immediateActions: result.optimizationRecommendations.immediateActions.map(action => ({
        ...action,
        strategy: action.strategy || '保持开放和理解的态度',
        example: action.example || '',
        applicability: action.applicability || 0,
        priority: action.priority || 'low'
      })),
      preventiveMeasures: result.optimizationRecommendations.preventiveMeasures.map(measure => ({
        ...measure,
        method: measure.method || '定期进行深入交流',
        example: measure.example || '',
        priority: measure.priority || 'low'
      }))
    }
  };
  conversationImported.value = true;
  showChatWindow.value = true;
  showChatButton.value = false;
};

// 处理聊天窗口关闭
const handleChatClose = () => {
  showChatWindow.value = false;
  showChatButton.value = true;
};

// 处理聊天消息
const handleChatMessage = (message: string) => {
  console.log('Received message:', message);
  // 这里可以添加处理消息的逻辑
};
</script>

<style lang="scss" scoped>
// 全局过渡动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease-out;
}

.slide-up-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.slide-up-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.analysis-container {
  padding: 1rem;
  max-width: 1600px;
  margin: 0 auto;
}

// 顶部通栏样式
.context-summary {
  background: linear-gradient(135deg, #6d28d9, #7c3aed);
  color: white;
  border-radius: 1rem;
  padding: 1.25rem;
  margin-bottom: 1rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  
  .context-summary-content {
    .context-summary-row {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem;
      align-items: center;
      justify-content: space-between;
    }
  }

  .metadata-overview {
    flex: 1;
    min-width: 300px;
    
    .metadata-items {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem;
      
      .metadata-item {
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        padding: 0.75rem;
        display: flex;
        flex-direction: column;
        min-width: 140px;
        flex: 1;
        
        .label {
          font-size: 0.75rem;
          text-transform: uppercase;
          letter-spacing: 0.05em;
          margin-bottom: 0.25rem;
          opacity: 0.8;
        }
        
        .value {
          font-size: 0.875rem;
          font-weight: 600;
        }
        
        .type-badge {
          display: inline-flex;
          align-items: center;
          padding: 0.25rem 0.5rem;
          border-radius: 1rem;
          font-size: 0.75rem;
          font-weight: 600;
          background-color: rgba(255, 255, 255, 0.15);
          
          &.工作沟通 {
            background-color: rgba(25, 118, 210, 0.3);
          }
          
          &.日常交流 {
            background-color: rgba(76, 175, 80, 0.3);
          }
          
          &.情感对话 {
            background-color: rgba(233, 30, 99, 0.3);
          }
          
          &.商业谈判 {
            background-color: rgba(255, 193, 7, 0.3);
          }
        }
      }
    }
  }
  
  .participant-cards {
    flex: 1;
    min-width: 300px;
    
    .participant-list {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem;
      justify-content: flex-end;
      
      .participant-card {
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        padding: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        min-width: 170px;
        flex: 1;
        max-width: 240px;
        transition: all 0.3s ease;
        
        &.active {
          background-color: rgba(255, 255, 255, 0.2);
          box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
        }
        
        .participant-avatar {
          position: relative;
          width: 2.75rem;
          height: 2.75rem;
          
          .avatar-model {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.2);
          }
          
          .emotion-bubble {
            position: absolute;
            bottom: -4px;
            right: -4px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            border: 2px solid rgba(255, 255, 255, 0.5);
            z-index: 1;
            
            &.positive {
              background-color: #4caf50;
            }
            
            &.negative {
              background-color: #f44336;
            }
            
            &.neutral {
              background-color: #9e9e9e;
            }
          }
        }
        
        .participant-info {
          flex: 1;
          
          .participant-name {
            font-size: 0.875rem;
            margin: 0 0 0.5rem 0;
            font-weight: 600;
          }
          
          .progress-ring {
            width: 100%;
            height: 6px;
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            margin-bottom: 0.25rem;
            overflow: hidden;
            
            .progress-fill {
              height: 100%;
              background-color: rgba(255, 255, 255, 0.5);
              transition: width 0.3s ease;
            }
          }
          
          .progress-text {
            font-size: 0.675rem;
            opacity: 0.8;
          }
        }
      }
    }
  }
}

// 分析区域样式
.analysis-main {
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 2rem;
    
    .empty-icon {
      color: #6d28d9;
      opacity: 0.5;
      margin-bottom: 1.5rem;
      animation: float 3s ease-in-out infinite;
    }
    
    .empty-title {
      font-size: 1.5rem;
      font-weight: 600;
      margin: 0 0 0.5rem;
      color: #1f2937;
    }
    
    .empty-text {
      font-size: 1rem;
      color: #6b7280;
      max-width: 500px;
      margin: 0 0 2rem;
    }
    
    .empty-features {
      display: flex;
      gap: 2rem;
      margin-bottom: 2rem;
      
      .feature-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .feature-icon {
          font-size: 2rem;
          margin-bottom: 0.5rem;
        }
        
        .feature-text {
          font-size: 0.875rem;
          color: #4b5563;
          font-weight: 500;
        }
      }
    }
  }
}

.analysis-sections {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

.analysis-section {
  background: white;
  border-radius: 1rem;
  padding: 1.5rem;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  
  &.chat-analysis-section {
    // 增强情感时间轴区域的样式，使其看起来更像聊天记录
    background-color: #f9f9f9;
    border: 1px solid #e5e7eb;
    
    .section-title {
      margin-bottom: 0.75rem;
      padding-bottom: 0.75rem;
      border-bottom: 1px solid #e5e7eb;
    }
    
    :deep(.conversation-display) {
      border: none;
      border-radius: 0;
      background-color: transparent;
      
      .conversation-title {
        display: none; // 隐藏重复的标题
      }
      
      .conversation-container {
        padding: 0.5rem;
        max-height: 500px; // 增加聊天记录的显示高度
      }
      
      .message {
        margin-bottom: 1rem;
        transition: transform 0.2s ease;
        
        &:hover {
          transform: translateY(-2px);
        }
      }
    }
    
    :deep(.timeline-visualization) {
      margin-top: 1.5rem;
      padding-top: 1.5rem;
      border-top: 1px dashed #e5e7eb;
    }
  }
  
  .section-title {
    display: flex;
    align-items: center;
    font-size: 1.25rem;
    font-weight: 600;
    color: #111827;
    margin: 0 0 1.5rem;
    
    .section-icon {
      margin-right: 0.75rem;
      font-size: 1.5rem;
    }
  }
}

// 响应式设计
@media (min-width: 1024px) {
  .analysis-sections {
    grid-template-columns: repeat(2, 1fr);
    
    .analysis-section:first-child,
    .analysis-section:nth-child(2) {
      grid-column: span 2;
    }
  }
}

// 深色模式
@media (prefers-color-scheme: dark) {
  .analysis-container {
    background-color: #1a1a1a;
  }

  .context-summary {
    background: linear-gradient(135deg, #5b21b6, #6d28d9);
  }

  .analysis-section {
    background-color: #242424;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2), 0 1px 2px 0 rgba(0, 0, 0, 0.12);
    
    &.chat-analysis-section {
      background-color: #2a2a2a;
      border-color: #3a3a3a;
      
      .section-title {
        border-bottom-color: #3a3a3a;
      }
      
      :deep(.timeline-visualization) {
        border-top-color: #3a3a3a;
      }
    }
    
    .section-title {
      color: #e5e7eb;
    }
  }

  .empty-state {
    .empty-title {
      color: #e5e7eb;
    }

    .empty-text {
      color: #9ca3af;
    }

    .feature-item .feature-text {
      color: #d1d5db;
    }
  }
}

// 动画
@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(0px);
  }
}
</style>
